﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CDSBDemandControl.Presenter;
using CDSBDemandControl.Model;
using System.Web.UI.HtmlControls;
using CDSBDemandControl.Configuration;

namespace CDSBDemandControl.View.Web.PaginasInternas
{
    public partial class Suporte : System.Web.UI.Page, IDiscriminatorDemand
    {
        private Presenter.DiscriminatorDemand Presenter;

        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Cache.SetExpires(DateTime.Now.Subtract(new TimeSpan(24, 0, 0)));
            Response.Cache.SetCacheability(HttpCacheability.NoCache);

            if (!this.IsPostBack || this.Session["Presenter"] == null)
            {
                this.Presenter = new DiscriminatorDemand(this);

                this.Session["Presenter"] = this.Presenter;

                if (!this.IsPostBack) this.ListarBugsProducao();
            }
            else
            {
                this.Presenter = (Presenter.DiscriminatorDemand)this.Session["Presenter"];
                this.Presenter.ResetView(this);
            }
        }

        private void ListarBugsProducao()
        {
            this.Presenter.ListProductionBugs();
        }
        
        public void ExibirBugsdeProducao(IEnumerable<DemandModel> demandModels)
        {
            List<EnumPriority> lstPriority = new List<EnumPriority>();

            lstPriority.Add(EnumPriority.Imediato);
            lstPriority.Add(EnumPriority.Urgente);
            lstPriority.Add(EnumPriority.Alta);
            lstPriority.Add(EnumPriority.Normal);
            lstPriority.Add(EnumPriority.Baixa);

            foreach (DemandModel md in demandModels)
            {
                if (md.Priority == EnumPriority.Unkown)
                    md.Priority = EnumPriority.Imediato;
            }

            foreach (EnumPriority en in lstPriority)
            {
                this.GenerateDinamicBugControls(en, demandModels.ToList().FindAll(delegate(DemandModel d) { return d.Priority == en; }),
                    lstPriority.FindIndex(delegate(EnumPriority ent) { return ent == en; }));
            }

            string Mensagem = demandModels.ToList().Count > 0 ? string.Empty : "Não há Bugs de Produção no Momento.";
            //// Exibe Mensagem quando não houver dados na Grid
            this.ValidarGridSemResultado(Mensagem, string.Empty);
            this.linkShow.Text = string.Format("Bugs no período de {0} à {1}.", ConfigManager.GetPeriodStartDate().ToBrazilianShortDateForUSAShortDate(), DateTime.Now.Date.ToShortDateString());

            // Exibe a data da última atualização
            (this.Master.FindControl("LblUltimoUpdate") as Label).Text = "Última atualização em: " + this.Presenter.DemandListLastUpdate.ToShortDateString() + " as " + this.Presenter.DemandListLastUpdate.ToShortTimeString();

            (this.Master.FindControl("txtTimeToCompare") as HtmlGenericControl).InnerHtml =
                this.Presenter.DemandListLastUpdate.Year + "," +
                (this.Presenter.DemandListLastUpdate.Month - 1) + "," +
                this.Presenter.DemandListLastUpdate.Day + "," +
                this.Presenter.DemandListLastUpdate.Hour + "," +
                this.Presenter.DemandListLastUpdate.Minute + "," +
                this.Presenter.DemandListLastUpdate.Second;
        }

        private void ValidarGridSemResultado(string msgSemResultado1, string msgSemResultado2)
        {
            this.DivMsgSemResultados1.Visible = (msgSemResultado1.Length > 0);
            this.lblMsgSemResultados1.Text = msgSemResultado1;

            this.DivMsgSemResultados2.Visible = (msgSemResultado2.Length > 0);
            this.lblMsgSemResultados2.Text = msgSemResultado2;
        }

        protected void CmbFiltro_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.ListarBugsProducao();
        }

        public void lnk_Click(object sender, EventArgs e)
        {
            if (linkShow.Text == "ExibirAtivos")
            { this.ListarBugsProducao(); }
            else
                this.Presenter.ListBugs();
        }

        public void ExibirBugsdeProducaoUltimoMes(List<DemandModel> BugList)
        {
            BugList = BugList.FindAll(delegate(DemandModel d)
            {
                bool ValidacaoModulo = (d.Project.ToLower() != "sinainfr" && !d.Project.ToLower().Contains("pse") && d.Project.ToLower() != "imercado");
                bool ValidacaoOrigem = (d.Origin == EnumOrigin.Corretora || d.Origin == EnumOrigin.Corretoras || d.Origin == EnumOrigin.Producao);

                return ValidacaoModulo && ValidacaoOrigem;
            }
            );

            List<EnumPriority> lstPriority = new List<EnumPriority>();

            lstPriority.Add(EnumPriority.Imediato);
            lstPriority.Add(EnumPriority.Urgente);
            lstPriority.Add(EnumPriority.Alta);
            lstPriority.Add(EnumPriority.Normal);
            lstPriority.Add(EnumPriority.Baixa);

            foreach (DemandModel md in BugList)
            {
                if (md.Priority == EnumPriority.Unkown)
                    md.Priority = EnumPriority.Imediato;
            }

            foreach (EnumPriority en in lstPriority)
            {
                this.GenerateDinamicBugControls(en, BugList.ToList().FindAll(delegate(DemandModel d) { return d.Priority == en; }),
                    lstPriority.FindIndex(delegate(EnumPriority ent) { return ent == en; }));
            }

            string Mensagem = BugList.ToList().Count > 0 ? string.Empty : "Não há Bugs de Produção no Momento.";
            
            // Exibe Mensagem quando não houver dados na Grid
            this.ValidarGridSemResultado(Mensagem, string.Empty);

            this.linkShow.Text = "ExibirAtivos";            
        }

        private void GenerateDinamicBugControls(EnumPriority en, List<DemandModel> list, int index)
        {
            list = list.OrderBy(bug => bug.DataIncFila).ToList();            

            List<string> fields = new List<string>();

            fields.Add("Id");
            fields.Add("Remedy");
            fields.Add("Projeto");
            fields.Add("Titulo");
            fields.Add("Gravidade");
            fields.Add("Responsável");
            //
            fields.Add("Início Estimado");
            fields.Add("Termino Estimado");
            fields.Add("Início");
            fields.Add("Termino");

            List<int> fieldsSize = new List<int>();

            fieldsSize.Add(25);
            fieldsSize.Add(25);
            fieldsSize.Add(100);
            fieldsSize.Add(400);
            fieldsSize.Add(100);
            fieldsSize.Add(200);
            //
            fieldsSize.Add(100);
            fieldsSize.Add(100);
            fieldsSize.Add(100);
            fieldsSize.Add(100);

            List<string> colors = new List<string>();

            colors.Add("#FF3300");
            colors.Add("#FF9933");
            colors.Add("#FFCC00");
            colors.Add("#FFFF99");
            colors.Add("#99CCFF");

            int numberOfCols = 10;
            int numberOfRows = list.Count + 1;

            Table tbl = new Table();
            TableRow r;
            TableCell c;

            tbl.Attributes.Add("cellspacing", "1");
            tbl.Attributes.Add("cellpadding", "4");
            tbl.Style.Add("background-color", "#333333");

            for (int i = 0; i <= numberOfRows; i++)
            {
                r = new TableRow();

                if (i > 1)
                {
                    r.Style.Add("align", "left");
                    r.Style.Add("background-color", "#FFFFFF");
                    r.Style.Add("font-family", "Verdana");
                    r.Style.Add("font-size", "X-Small");
                }
                else
                {
                    r.Attributes.Add("align", "center");

                    r.Style.Add("background-color", colors[index]);

                    r.Style.Add("font-family", "Verdana");
                    r.Style.Add("font-size", "X-Small");
                    r.Style.Add("font-weight", "bold");

                    if (i == 0)
                    {
                        c = new TableCell();
                        c.Attributes.Add("colspan", "10");

                        c.Controls.Add(new LiteralControl(en.ToString()));
                        r.Cells.Add(c);
                    }
                }

                for (int j = 0; j < numberOfCols; j++)
                {
                    if (i != 0)
                    {
                        if (i == 1)
                        {
                            c = new TableCell();
                            c.Controls.Add(new LiteralControl(fields[j]));
                            c.Width = fieldsSize[j];
                            r.Cells.Add(c);
                        }
                        else
                        {
                            List<string> values = new List<string>();

                            string idWorkItem = @"<a href='http://utilcorp05:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker={0}' target='_blank'>{0}</a>";
                            string idRemedy = @"<a href='http://sinacorint1/cvsa/consultaremedy/listachamadosRemedy.aspx?IdIncidente=INC000000{0}' target='_blank'>{0}</a>";
                            
                            values.Add(string.Format(idWorkItem, list[i - 2].ID));
                            values.Add(string.IsNullOrEmpty(list[i - 2].Remedy) ? "N/A" : string.Format(idRemedy, list[i - 2].Remedy));
                            values.Add(list[i - 2].Project);
                            values.Add(list[i - 2].Title);
                            values.Add(list[i - 2].Gravity.ToString());

                            string aux = list[i - 2].Responsible;

                            if (string.IsNullOrEmpty(aux))
                                aux = ((CDSBDemandControl.Model.DemandModelBase)(list[i - 2])).AssignedTo;

                            values.Add(aux);

                            values.Add
                                ((list[i - 2].EstimatedStart.HasValue) ? list[i - 2].EstimatedStart.Value.ToShortDateString() + " " + list[i - 2].EstimatedStart.Value.ToShortTimeString()
                                :
                                    string.Empty
                                );
                            values.Add
                                ((list[i - 2].EstimatedConclude.HasValue) ? list[i - 2].EstimatedConclude.Value.ToShortDateString() + " " + list[i - 2].EstimatedConclude.Value.ToShortTimeString()
                                :
                                    string.Empty
                                );
                            values.Add
                                ((list[i - 2].Start.HasValue) ? list[i - 2].Start.Value.ToShortDateString() + " " + list[i - 2].Start.Value.ToShortTimeString()
                                :
                                    string.Empty
                                );
                            values.Add
                                ((list[i - 2].Conclude.HasValue) ? list[i - 2].Conclude.Value.ToShortDateString() + " " + list[i - 2].Conclude.Value.ToShortTimeString()
                                :
                                    string.Empty
                                );

                            c = new TableCell();
                            c.Controls.Add(new LiteralControl(values[j]));
                            r.Cells.Add(c);
                        }
                    }
                }

                tbl.Rows.Add(r);
            }

            if (tbl.Rows.Count > 2)
            {
                DivSuporte.Controls.Add(tbl);
                DivSuporte.Controls.Add(new LiteralControl("<br />"));
            }
        }

        #region IDiscriminatorDemand Members

        void IDiscriminatorDemand.ExibirFila(IEnumerable<CDSBDemandControl.Model.DemandModel> demandModels)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirEsteira(IEnumerable<CDSBDemandControl.Model.DemandModel> demandModels)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirRanking(IEnumerable<CDSBDemandControl.Model.DeveloperModel> developers, IEnumerable<CDSBDemandControl.Model.DeveloperModel> leaders, IEnumerable<CDSBDemandControl.Model.DeveloperModel> focalpoints)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirAtrasos(IEnumerable<CDSBDemandControl.Model.DemandModel> PendingDemands, IEnumerable<CDSBDemandControl.Model.DemandModel> Concludeddemands)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirFaturamento(List<CDSBDemandControl.Model.BillingModel> billing, bool canSeeBilling)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirScenariosAndTasks(List<CDSBDemandControl.Model.ScenarioModel> scenarios)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirCodeReview(IEnumerable<CDSBDemandControl.Model.DemandModel> WorkItemsWithCodeReview, IEnumerable<CDSBDemandControl.Model.DemandModel> WorkItemsWithoutCodeReview)
        {
            throw new NotImplementedException();
        }        

        void IDiscriminatorDemand.ExibirListaDisp(IEnumerable<CDSBDemandControl.Model.DemandModel> list, IEnumerable<CDSBDemandControl.Model.DeveloperModel> modelAusencias, List<DateTime> fer)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirFactoryWaitingList(List<CDSBDemandControl.Model.BillingModel> Billing, bool AllowsShow)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirAlocacao(IEnumerable<CDSBDemandControl.Model.DemandModel> demandModels)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirFactoryProductionList(List<BillingModel> billing, bool canSeeBilling)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirSolicitacoesSites(List<CDSBDemandControl.Model.DemandModel> demandModels)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirManagementTeamTasks(List<CDSBDemandControl.Model.DemandModel> demandModels)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
